package crm8000.services

import crm8000.Models.FId;
import crm8000.Models.MenuItem;
import crm8000.Models.User;
import grails.transaction.Transactional

@Transactional
class InitDBService {
	
	def IdGenService idGenService

    def init() {
		initUser()
		
		initFid()
		
		initMainMenu()	
    }
	
	def private initUser() {
		def user = User.findByLoginName("admin")
		
		if (!user) {
			new User(userId: idGenService.newId(), loginName: "admin",
				name: "系统管理员", password: "admin".encodeAsMD5()).save()
		}
	}
	
	def private initMainMenu() {
		if (MenuItem.count() > 0) {
			return
		}
		
		// 菜单：文件
		def menuId = idGenService.newId()
		new MenuItem(menuId: menuId, parentId: null, caption: "文件", showOrder: 1, fid: null).save()
		new MenuItem(menuId: idGenService.newId(), parentId: menuId, caption: "首页", showOrder: 1, fid: "-9997").save()
		new MenuItem(menuId: idGenService.newId(), parentId: menuId, caption: "重新登录", showOrder: 2, fid: "-9999").save()
		new MenuItem(menuId: idGenService.newId(), parentId: menuId, caption: "修改我的密码", showOrder: 3, fid: "-9996").save()
		
		// 菜单：基础数据
		menuId = idGenService.newId()
		new MenuItem(menuId: menuId, parentId: null, caption: "基础数据", showOrder: 8, fid: null).save()
		new MenuItem(menuId: idGenService.newId(), parentId: menuId, caption: "商品", showOrder: 1, fid: "1001").save()
		
		// 菜单：系统管理
		menuId = idGenService.newId()
		new MenuItem(menuId: menuId, parentId: null, caption: "系统管理", showOrder: 9, fid: null).save()
		new MenuItem(menuId: idGenService.newId(), parentId: menuId, caption: "用户管理", showOrder: 1, fid: "-8999").save()
		new MenuItem(menuId: idGenService.newId(), parentId: menuId, caption: "权限管理", showOrder: 1, fid: "-8996").save()
		new MenuItem(menuId: idGenService.newId(), parentId: menuId, caption: "系统日志", showOrder: 1, fid: "-8997").save()
		
	}
	
	def private initFid() {
		if (FId.count() > 0) {
			return
		}
		
		new FId(fid: "-9999", name: "重新登录").save()
		new FId(fid: "-9997", name: "首页").save()
		new FId(fid: "-9996", name: "修改我的密码").save()
		new FId(fid: "-8999", name: "用户管理").save()
		new FId(fid: "-8997", name: "系统日志").save()
		new FId(fid: "-8996", name: "权限管理").save()
		new FId(fid: "1001", name: "商品").save()
		new FId(fid: "1002", name: "商品计量单位").save()
		new FId(fid: "1003", name: "仓库").save()
		new FId(fid: "1004", name: "供应商档案").save()
		new FId(fid: "1007", name: "客户资料").save()
		new FId(fid: "2000", name: "库存建账").save()
		new FId(fid: "2001", name: "采购入库").save()
	}
}
